<?php
/**
 * 后台管理员登录
 */
defined('BASEPATH') OR exit("No direct script access allowed");

class Login extends CI_Controller{


	//构造初始化函数
	public function __construct(){
		parent::__construct();

		//加载数据库
		$this->load->database();

		//加载admin模型
		$this->load->model('admin/DoctorJ_model','doctorJ');

		//加载表单验证规则
		$this->load->library('form_validation');
		date_default_timezone_set("PRC");

	}

	public function login()
	{
		//设置验证规则
		$this->form_validation->set_rules('openid','用户名','required');

	    //先验证规则
		if($this->form_validation->run()==false){
				$result=array(
						'isSuccess'=>'0',
						'msg'=>'openid为空'
				);
				$this->printJson($result);
			exit();
		}

			$openid=$this->input->post('openid',TRUE);
			if ($this->doctorJ->cheByOpenid($openid)){
				//如果存在这个openid
				$this->session->set_userdata('fresh',md5($openid));


				$data['DoctorOne']=$this->doctorJ->getOneByOpenid($openid);
				//print_r($data);
				$result=array(
						'isSuccess'=>'1',
						'msg'=>'登录成功',
						'session'=>$this->session->userdata('fresh'),
					    'id'=>$data['DoctorOne']['id'],
					    'mobile'=>$data['DoctorOne']['mobileJ'],
					    'realName'=>$data['DoctorOne']['realNameJ'],
					    'group'=>$data['DoctorOne']['groupJ'],
					    'hostpital'=>$data['DoctorOne']['hostpitalJ'],
					    'depar'=>$data['DoctorOne']['deparJ'],
					    'dateTime'=>$data['DoctorOne']['dateTimeJ']
				);
				$this->printJson($result);
			}
			else{
				//如果不存在这个openid,往数据库注册
				$this->session->set_userdata('fresh',md5($openid));

				$data['weichatJ']=$openid;
				$data['dateTimeJ']='20'.date("y-m-d",time());
				if($this->doctorJ->addOne($data)){
				  	$result=array(
						'isSuccess'=>'2',
						'msg'=>'第一次登陆，添加成功',
						'session'=>$this->session->userdata('fresh')
					);
					$this->printJson($result);
				}else{
					  	$result=array(
							'isSuccess'=>'0',
							'msg'=>'登录失败',
					);
					$this->printJson($result);
				}
			}
	}

	//测试之用
	public function test()
	{
		$this->load->view("api/form.html");

	}

	public function printJson($result){
		foreach ( $result as $key => $value ) {
					$result[$key] = urlencode ( $value );
				}
				echo urldecode ( json_encode ( $result ) );
	}

}
